package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    /**
     * 登录功能
     *
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {

        //1.根据用户名查找用户
        Employee loginEmployee = employeeMapper.login(employee);

        //2.判断密码是否正确
        String password=employee.getPassword();
        String loginPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!(loginEmployee!=null&&loginEmployee.getPassword().equals(loginPassword))){
            //密码不正确
            return null;
        }
        if (loginEmployee!=null&&loginEmployee.getStatus()!=1){
            //状态禁用
            return null;
        }
        return loginEmployee;

    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @Override
    public Boolean addEmployee(Employee employee) {
        return employeeMapper.addEmployee(employee)>0;
    }

    /**
     * 根据名字分页查询
     *
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page findByPage(String name, long page, long pageSize) {
        //1.查询总条数
        Long total = employeeMapper.count(name);
        //2.查询每页数据
        List<Employee> employeeList = employeeMapper.findAll(name, (page - 1) * pageSize, pageSize);
        //3.返回封装结果
        Page<Employee> employeePage = new Page<>();
        employeePage.setPageSize(pageSize);
        employeePage.setPage(page);
        employeePage.setTotal(total);
        employeePage.setRecords(employeeList);
        return employeePage;
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    /**
     * 修改员工信息
     *
     * @param employee
     * @return
     */
    @Override
    public Boolean update(Employee employee) {
        return employeeMapper.update(employee)>0;
    }


}
